package com.smsp.dao.impl;

import com.smsp.common.Const;
import com.smsp.common.ServerResponse;
import com.smsp.dao.MessageWay;
import com.smsp.util.HttpUtil;
import com.smsp.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessageWayImpl implements MessageWay {

    public Logger logger = LoggerFactory.getLogger(MessageWayImpl.class);
    @Override
    public ServerResponse sendMessage(String phone, String messageContent, String sign, String extno) {
        //短信通道用户密码MD5加密
        String md5Password = MD5Util.encode2hex(Const.MESSAGE_WAY_PASSWORD);

        //对下发短信内容进行编码处理
        String newcontent = null;
        try {
            logger.info(messageContent+"编码为64位字节流成功");
            /*添加上签名*/
            messageContent ="【"+sign+"】"+messageContent;
            newcontent =java.util.Base64.getUrlEncoder().encodeToString(messageContent.getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {
            logger.debug("短信内容字节流编码失败");
            e.printStackTrace();
//            return Const.MESSAGE_CONTENT_CODE_FAIL;
            return ServerResponse.createByErrorCodeMessage(Const.MESSAGE_CONTENT_CODE_FAIL,"短信内容编码失败");
        }
        Map params = new HashMap(6);

        params.put("user",Const.MESSAGE_WAY_USER);
        params.put("pwd",md5Password);
        params.put("mobile",phone);
        params.put("msg",newcontent);
        params.put("extno",extno);

        String response = HttpUtil.sendGet(Const.MESSAGE_WAY_URL,params);
        List<String> responeList = java.util.Arrays.asList(response.split(","));
        if(responeList==null){
            logger.debug("短信通道服务器错误");
            return ServerResponse.createByErrorCodeMessage(Const.MESSAGE_WAY_REQUEST_ERROR,"短信通道服务器错误");
        }
        return ServerResponse.cerateBySuccess(responeList);
    }

    @Override
    public ServerResponse queryMessageDetail(String msgid) {
        String md5Password = MD5Util.encode2hex(Const.MESSAGE_WAY_PASSWORD);
        Map params = new HashMap(6);

        params.put("user",Const.MESSAGE_WAY_USER);
        params.put("pwd",md5Password);
        params.put("msgid",msgid);

        String response = HttpUtil.sendGet(Const.MESSAAGE_QUERYWAY_URL,params);
        List<String> responeList = java.util.Arrays.asList(response.split(","));
        if(responeList==null){
            logger.debug("短信查询通道服务器错误");
            return ServerResponse.createByErrorCodeMessage(Const.MESSAGE_WAY_REQUEST_ERROR,"短信查询通道服务器错误");
        }
        return ServerResponse.cerateBySuccess(responeList);
    }
}
